import 'package:flutter/material.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:kxy_flutter_app/auth.dart';
import 'package:kxy_flutter_app/components/empty_widget.dart';
import 'package:kxy_flutter_app/components/loading_widget.dart';
import 'package:kxy_flutter_app/components/refresh_header.dart';
import 'package:kxy_flutter_app/helper/http.dart';
import 'package:kxy_flutter_app/model/exam.dart';
import 'package:kxy_flutter_app/model/exam_category.dart';
import 'package:kxy_flutter_app/view/examination/template/spec_exam_widget.dart';
import 'package:kxy_flutter_app/view/examination/template/timeline_exam_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import 'template/official_exam_widget.dart';

class CategoryExamListView extends StatefulWidget {
  final ExamCategory category;

  CategoryExamListView({@required this.category});

  @override
  State<StatefulWidget> createState() {
    return new ExaminationListState();
  }
}

class ExaminationListState extends State<CategoryExamListView> {
  RefreshController controller = new RefreshController();
  List<Exam> examList = new List<Exam>();
  Future loadFuture;

  @override
  void initState() {
    loadFuture = reload();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.category.name)),
      body: FutureBuilder(
        future: loadFuture,
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            return examListWidget();
          }
          return LoadingWidget();
        },
      ),
    );
  }

  Widget examListWidget() {
    if (examList.length == 0) {
      return EmptyWidget(onRefresh: reload);
    }

    Widget examWidget;
    if (widget.category.templateNum == 0) {
      examWidget = OfficialExamWidget(
        examList: examList,
        refresh: reload,
      );
    } else if (widget.category.templateNum == 1) {
      examWidget = TimelineExamWidget(
        examList: examList,
        refresh: reload,
      );
    } else {
      examWidget = SpecExamWidget(
        examList: examList,
        refresh: reload,
      );
    }

    return SmartRefresher(
      controller: controller,
      enablePullDown: true,
      enablePullUp: false,
      header: RefreshHeader(),
      child: SingleChildScrollView(
        child: examWidget,
      ),
      onRefresh: () async {
        await reload();
        controller.refreshCompleted();
      },
    );
  }

  Future reload() async {
    var res = await Http.instance.post(
      '/exam-app/exam/examList',
      params: {
        'cateId': widget.category.id,
        'userId': Auth.instance.userId,
        'publisherScope': 1,
      },
    );

    if (res.code == 200) {
      setState(() {
        examList = (res.data as List).map((e) => Exam.fromJson(e)).toList();
      });
    } else {
      Fluttertoast.showToast(msg: res.msg);
    }
  }
}
